/**
 * 客户标签
 */
'use strict';
define(['app', 'js/directive/listTree', 'js/filter/tree2Arr', 'datetime', 'autocomplete', 'pagination', 'editor', 'filesaver', 'fileupload'], function(app) {

    app.controller('Fine', function($scope, dataFactoryCRM, $q) {

        $scope.finePages = {
            pageAll: 1,
            pageNow: 1,
            pageSize: $scope.psize,
            k: 3
        };
        /**局部信息 */
        $scope.sectors = {};
        $scope.users = {};
        $scope.userss = {};
        $scope.manager = {};
        $scope.managers = {};
        $scope.index = 'false';
        /**检索条件 */
        $scope.search = { start_time: '', end_time: '', sales_sector: '', sales_id: '', sales_name: '' };
        /**添加元素 */
        $scope.add = { title: '', fine_num: '', theme: '', description: '', reply_action: '', isAddUser: false, };
        /**添加罚单关联人员 */
        $scope.addFineUsers = new Array();
        $scope.addFineUserItem = { fine_type: '', fine_mount: '', fine_remark: '', sales_id: '', name: '', sales_sector: '', sales_manager: '', sales_managername: '', sector_name: '', fine_content: '' };
        /**编辑条件 */
        $scope.update = {};

        /**获取部门信息 */
        $scope.getSector = function() {
            var _url = 'Fine/index';
            dataFactoryCRM.getDataByAPI(_url).then(function(_d) {
                if (_d.rcode) {
                    $scope.sectors = _d.data;
                }
            });
        };
        /*获取违规主题词系统参数表*/
        $scope.getSysParam = function() {
            var _url = 'Fine/getSysParam?key_name=' + 'FINE_THEME';
            dataFactoryCRM.getDataByAPI(_url).then(function(_d) {
                if (_d.rcode) {
                    $scope.sys_param = _d.data;
                }
            });
        };

        /***************************************************************增删改查基础功能******************************************************** */

        /**获取罚款单信息 */
        $scope.getFine = function() {
            if ($scope.search.sales_name && !$scope.search.sales_id) $scope.search.sales_id = -1;
            if (!$scope.search.sales_name) $scope.search.sales_id = '';
            $scope.$emit('BUSY');
            var _url = 'Fine/getFine?p=' + $scope.finePages.pageNow + '&psize=' + $scope.finePages.pageSize + '&start_time=' + $scope.search.start_time + '&end_time=' + $scope.search.end_time + '&sales_name=' + $scope.search.sales_name;
            dataFactoryCRM.getDataByAPI(_url).then(function(response) {
                $scope.$emit('NOTBUSY');
                if (response.rcode) {
                    $scope.finePages.pageSize = response.psize;
                    $scope.finePages.pageAll = response.pall;
                    $scope.finePages.pageNow = response.p;
                    $scope.fine = response.data;
                } else {
                    $scope.fine = '';
                    $scope.finePages.pageNow = 1;
                    $scope.finePages.pageAll = 1;
                }
            });
        };
        //初始化页面显示数据（如果是新弹出独立窗口则从父窗口获取）
        window.loadClientCacheToScope($scope, function() {
            $scope.getFine();
        });
        
        /**添加罚款单信息 */
        $scope.addFine = function() {

            function init() {
                $scope.isAddUser = false;
                $scope.addFineUsers = new Array();
                $scope.addFineUserItem = {};
                $scope.add = {};
            }

            init();
            $scope.$broadcast('angucomplete-alt:clearInput');
            $('.frm.add').form('reset');

            $scope.addFineUserItem.sales_sector = 1;
            setTimeout(function() { $('.ui.dropdown').dropdown() }, 50);
            $('.ui .addFine').modal({
                observeChanges: true,
                onApprove: function() {
                    if ($scope.isAddUser) {
                        alert('请点击保存或者取消按钮结束操作');
                        return false;
                    }
                    if ($scope.addFineUsers.length == 0) {
                        alert('请添加罚款人之后再进行保存操作');
                        return false;
                    }
                    if ($('.frm.add').form('is valid')) {
                        $scope.commitAdd();
                        return true;
                    } else {
                        if (!$('#add_description1').val() || !$('#add_reply_action1').val()) {
                            alert('请继续完善违规情况说明和处理方案');
                            return false;
                        }
                        return false;
                    }
                }
            }).modal('show');
        };
        $scope.commitAdd = function() {
            /**添加成功 */
            function addSuccess() {
                setTimeout(function() {
                    $('.modal1').modal('show');
                    //3s后关闭
                    setTimeout(function() {
                        $('.modal1').modal('hide')
                    }, 3000)
                }, 1000);
            }
            /**添加失败 */
            function addFail() {
                //添加失败了,
                setTimeout(function() {
                    $('.modal2').modal('show');
                    //3s后关闭
                    setTimeout(function() {
                        $('.modal2').modal('hide')
                    }, 3000)
                }, 1000);
            }

            /**自动生成风控号 */
            var date = new Date();
            var year = date.getFullYear();
            var month = date.getMonth() + 1;
            var day = date.getDate();
            var hour = date.getHours();
            var minute = date.getMinutes();
            var second = date.getSeconds();
            $scope.add.fine_num = '（' + year + '）' + month + day + hour + minute + second;
            var post = {};
            post.fine = $scope.add;
            post.fine_user = $scope.addFineUsers;
            $scope.$emit('BUSY');
            $scope.busy = dataFactoryCRM.postDataByAPI('Fine/addFine', post)
                .then(function(response) {
                    $scope.fineRcode = response.rcode;
                    if (response.rcode) {
                        addSuccess();
                        $scope.getFine();
                    } else {
                        $scope.$emit('NOTBUSY');
                        addFail();
                    }
                });
        };

        /**更新罚款单信息 */
        $scope.updateFine = function() {

            function init() {
                $scope.isAddUser = false;
                $scope.update = {};
                $scope.addFineUsers = new Array();
                $scope.addFineUserItem = {};
            }
            init();

            $scope.update = this.vfine;
            $scope.addFineUsers = this.vfine.fine_user;

            setTimeout(function() { $('.ui.theme.dropdown').dropdown() }, 50);

            $('.ui .updateFine').modal({
                observeChanges: true,
                onApprove: function() {
                    if ($scope.isAddUser) {
                        alert('请点击保存或者取消按钮结束操作');
                        return false;
                    }
                    if ($scope.addFineUsers.length == 0) {
                        alert('请添加罚款人之后再进行保存操作');
                        return false;
                    }
                    if ($('#frm-update').form('is valid')) {
                        $scope.commitUpdate();
                        return true;
                    } else {
                        if (!$('#update_description3').val() || !$('#update_reply_action3').val()) {
                            alert('请继续完善违规情况说明和处理方案');
                            return false;
                        }
                    }
                    return false;
                },
                onDeny: function() {
                    $scope.getFine();
                }
            }).modal('show');
        };
        $scope.commitUpdate = function() {

            /**更新成功 */
            function updateSuccess() {
                setTimeout(function() {
                    $('.modal4').modal('show');
                    //3s后关闭
                    setTimeout(function() {
                        $('.modal4').modal('hide')
                    }, 3000)
                }, 1000);
            }
            /**更新失败 */
            function updateFail() {
                //添加失败了,
                setTimeout(function() {
                    $('.modal5').modal('show');
                    //3s后关闭
                    setTimeout(function() {
                        $('.modal5').modal('hide')
                    }, 3000)
                }, 1000);
            }

            var post = {};
            post.fine = $scope.update;
            post.fine_user = $scope.addFineUsers;
            $scope.$emit('BUSY');
            $scope.busy = dataFactoryCRM.postDataByAPI('Fine/updateFine', post)
                .then(function(response) {
                    if (response.rcode) {
                        updateSuccess();
                        $scope.getFine();
                    } else {
                        $scope.$emit('NOTBUSY');
                        updateFail();
                    }
                });
        };

        /**删除罚款单信息 */
        $scope.delFine = function() {
            var fine = this.vfine;
            $('.ui .modal3').modal({
                observeChanges: true,
                onApprove: function() {
                    $scope.commitDel(fine);
                    return true;
                }
            }).modal('show');
        };
        $scope.commitDel = function(fine) {
            $scope.$emit('BUSY');
            $scope.busy = dataFactoryCRM.postDataByAPI('Fine/delFine', fine)
                .then(function(response) {
                    if (response.rcode) {
                        $scope.getFine();
                    }
                });
        };
        /**导入罚款单信息 */
        $scope.importFine = function() {
            alert('import');
        };
        /**导出罚款单信息 */
        $scope.exportFine = function() {
            $scope.$emit('BUSY');
            var _url = 'Fine/exportFine?start_time=' + $('#start_time').val() + '&end_time=' + $('#end_time').val() + '&sales_name=' + $scope.search.sales_name;
            dataFactoryCRM.getDataByAPIS(_url).then(function(response) {
                $scope.$emit('NOTBUSY');
                var blob = new Blob([response], {
                    type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                });
                saveAs(blob, '罚款单数据记录表' + '.xls');
            });
        };
        /**普通用户查看罚款单详情 */
        $scope.lookFine = function() {
            $scope.update = this.vfine;
            $scope.addFineUsers = this.vfine.fine_user;
            setTimeout(function() {
                $('.view_wangEditor').attr("contenteditable", "false");
            }, 50);
            $('.ui .lookFine').modal({
                observeChanges: true,
            }).modal('show');
        };

        /***************************************************************筛选操作******************************************************** */

        /**在检索框筛选目标对象 */
        $scope.selectUserOfSearch = function(selected) {
            if (selected) {
                $scope.search.sales_id = selected.originalObject.user_id;
            }
        };

        /***********************************************************罚款单关联人员操作****************************************************** */

        /**显示添加罚款相关人员信息输入界面 */
        $scope.addFineUser = function() {
            $scope.isAddUser = true;
            $scope.addFineUserItem.sales_sector = 1;
            setTimeout(function() { $('.ui.dropdown').dropdown() }, 100);
            return true;
        };
        /**隐藏添加罚款相关人员信息输入界面 */
        $scope.addFineUserNo = function() {
            $scope.index = 'false';
            $scope.addFineUserItem = {};
            $('#meme_value').val('');
            $('#youyou_value').val('');
            $('.frm.user').form('reset');
            $scope.addFineUserItem.sales_sector = 1;
            setTimeout(function() { $('.ui.dropdown').dropdown() }, 50);
            $scope.isAddUser = false;
            return true;
        };
        /**自动补全罚款人员请求目标对象 */
        $scope.selectSector = function(sector_id) {
            var _url = 'Fine/getUserByID?sector_id=' + sector_id;
            dataFactoryCRM.getDataByAPI(_url).then(function(response) {
                if (response.rcode) {
                    if (sector_id == 0) {
                        $scope.userss = response.data;
                    }
                    $scope.users = response.data;
                } else {
                    $scope.users = [{}];
                }
            });
        };
        /**自动补全获取目标对象 */
        $scope.selectUser = function(selected) {
            if (selected) {
                $scope.addFineUserItem.sales_id = selected.originalObject.user_id;
                $scope.addFineUserItem.name = selected.originalObject.nickname;
                $scope.addFineUserItem.sales_sector = selected.originalObject.sales_sector;
                $scope.addFineUserItem.sales_manager = selected.originalObject.manager_id;
                $scope.addFineUserItem.sales_managername = selected.originalObject.manager_name;
                $scope.addFineUserItem.sales_subcompany = selected.originalObject.is_subcompany == '1' ? selected.originalObject.sales_sector : selected.originalObject.parent_company;
                setTimeout(function() { $('.ui.dropdown').dropdown() }, 50);
            }
        };

        /**在添加界面编辑关联人信息 */
        $scope.updateFineUserOfAdd = function() {
            $scope.addFineUser();
            $scope.index = this.$index;
            $scope.addFineUserItem = this.vfineUser;
            $scope.addFineUserItem.fine_content = $scope.addFineUserItem.fine_type == 1 ? $scope.addFineUserItem.fine_mount : $scope.addFineUserItem.fine_remark;
            $('#meme_value').val($scope.addFineUserItem.name);
            $scope.selectSector($scope.addFineUserItem.sales_sector);
            setTimeout(function() { $('.ui.dropdown').dropdown() }, 50);
        };
        /**在编辑界面编辑关联人信息 */
        $scope.updateFineUserOfUpdate = function() {
            $scope.addFineUser();
            $scope.index = this.$index;
            $scope.addFineUserItem = this.vfineUser;
            $scope.addFineUserItem.fine_content = $scope.addFineUserItem.fine_type == 1 ? $scope.addFineUserItem.fine_mount : $scope.addFineUserItem.fine_remark;
            $('#youyou_value').val($scope.addFineUserItem.name);
            $scope.selectSector($scope.addFineUserItem.sales_sector);
            setTimeout(function() { $('.ui.dropdown').dropdown() }, 50);
        };
        /**删除关联人信息 */
        $scope.delFineUser = function() {
            $scope.index = this.$index;
            $scope.addFineUsers.splice($scope.index, 1);
        };
        /**拼接新增关联人 */
        $scope.saveFineItem = function(key) {
            /**判断表单是或否位空 */
            if (!$scope.addFineUserItem.sales_sector || !$scope.addFineUserItem.sales_id || !$scope.addFineUserItem.fine_type || !$scope.addFineUserItem.fine_content || !$scope.addFineUserItem.sales_manager || !($('#meme_value').val() || $('#youyou_value').val())) {
                if (!$scope.addFineUserItem.sales_sector) {
                    alert('请选择所属部门');
                    return false;
                }
                if (!$scope.addFineUserItem.sales_id) {
                    alert('请输入正确的业务员姓名');
                    return false;
                }
                if (!$scope.addFineUserItem.sales_manager) {
                    alert('请输入正确的经理姓名');
                    return false;
                }
                if (!$scope.addFineUserItem.fine_type) {
                    alert('请选择处罚类型');
                    return false;
                }
                if (!$scope.addFineUserItem.fine_content) {
                    alert('请输入处罚内容');
                    return false;
                }
            }　
            /**判断金额处罚类型的处罚内容是否位数字 */
            var re = /^[0-9]+.?[0-9]*$/; //判断字符串是否为数字 //判断正整数 /^[1-9]+[0-9]*]*$/ 
            if (($scope.addFineUserItem.fine_type == 1) && (!re.test($scope.addFineUserItem.fine_content))) {　　　　
                alert("处罚金额类型必须为数字");　　　　
                return false;　　
            }　
            if ($scope.addFineUserItem.fine_type == 1) {
                $scope.addFineUserItem.fine_mount = $scope.addFineUserItem.fine_content;
            } else if ($scope.addFineUserItem.fine_type == 2) {
                $scope.addFineUserItem.fine_remark = $scope.addFineUserItem.fine_content;
            }
            /**合并数据集 */
            $scope.index != 'false' ? $scope.addFineUsers.splice($scope.index, 1, $scope.addFineUserItem) : $scope.addFineUsers.push($scope.addFineUserItem);
            /**关闭新增窗口 */
            8
            $scope.isAddUser = false;
            /**清空填写区间 */
            $scope.index = 'false';
            $scope.addFineUserItem = {};
            key == 'add' ? $('#meme_value').val('') : $('#youyou_value').val('');
            $('.frm.user').form('reset');
            $scope.$broadcast('angucomplete-alt:clearInput');
            setTimeout(function() { $('.ui.dropdown').dropdown() }, 50);
        };

        /***************************************************************罚款单关联人员操作******************************************************** */

        /**加载用户 */
        $scope.load_user = function(_name) {
            var deferred = $q.defer();
            if (_name) {
                $scope.busy = dataFactoryCRM.postDataByAPI('user/searchByName', { 'name': _name })
                    .then(function(d) {
                        deferred.resolve(d);
                    });
            } else
                deferred.reject('参数提交错误');
            return deferred.promise;
        };
        /**监听经理 */
        $scope.$watch('addFineUserItem.sales_managername', function(newValue, oldValue) {
            if (newValue == oldValue) return true;
            $scope.load_user(newValue).then(function(d) {
                if (d && 1 == d.rcode) {
                    $scope.addFineUserItem.sales_manager = d.data.user_id;
                    $scope.addFineUserItem.sales_managername = d.data.nickname;
                } else if (d && 0 == d.rcode) {
                    $scope.addFineUserItem.sales_manager = '';
                    $scope.addFineUserItem.sales_managername = '';
                }
            });
        });
        /**监听搜索框业务人员 */
        // $scope.$watch('search.sales_name', function(newValue, oldValue) {
        //     if (newValue == oldValue) return true;
        //     $scope.load_user(newValue).then(function(d) {
        //         if (d && 1 == d.rcode) {
        //             $scope.search.sales_id = d.data.user_id;
        //             $scope.search.sales_name = d.data.nickname;
        //         } else if (d && 0 == d.rcode) {
        //             $scope.search.sales_id = '';
        //             $scope.search.sales_name = '';
        //         }
        //     });
        // });
        $scope.$watch('addFineUserItem.sales_sector', function(newValue, oldValue) {
            if (newValue == oldValue) return true;
            $scope.selectSector(newValue);
        });

        /***********************************表单验证*************************************** */

        /**add监听违规情况说明 */
        $scope.$watch('add.description', function(newValue, oldValue) {
            if (newValue == oldValue) return true;
            if (newValue != undefined) {
                var value = JSON.stringify($scope.add.description);
                value = value.replace(/<.*?>/ig, "");
                $('#add_description1').val(value);
                setTimeout(function() { $('#add_description1').trigger('blur'); }, 50);
            }
        })

        /**add监听处理方案 */
        $scope.$watch('add.reply_action', function(newValue, oldValue) {
            if (newValue == oldValue) return true;
            if (newValue != undefined) {
                var value = $scope.add.reply_action;
                value = value.replace(/<.*?>/ig, "");
                $('#add_reply_action1').val(value);
                setTimeout(function() { $('#add_reply_action1').trigger('blur'); }, 50);
            }
        })

        /**update监听违规情况说明 */
        $scope.$watch('update.description', function(newValue, oldValue) {
            if (newValue == oldValue) return true;
            if (newValue != undefined) {
                var value = $scope.update.description;
                value = value.replace(/<.*?>/ig, "");
                $('#update_description3').val(value);
                setTimeout(function() { $('#update_description3').trigger('blur'); }, 50);
            }
        })

        /**update监听处理方案 */
        $scope.$watch('update.reply_action', function(newValue, oldValue) {
            if (newValue == oldValue) return true;
            if (newValue != undefined) {
                var value = $scope.update.reply_action;
                value = value.replace(/<.*?>/ig, "");
                $('#update_reply_action3').val(value);
                setTimeout(function() { $('#update_reply_action3').trigger('blur'); }, 50);
            }
        })

        /**自动补全多余输入 */
        $scope.userInputChanged = function($item) {
            $scope.checkUser = $item;
        };

        $scope.$watch('checkUser', function(newValue, oldValue) {
            if (newValue == oldValue) return true;
            if ((newValue != $scope.addFineUserItem.name) && oldValue) {
                $('#meme_value').val('');
                $('#youyou_value').val('');
                $scope.addFineUserItem.sales_id = '';
                $scope.addFineUserItem.name = '';
                $scope.addFineUserItem.sales_managername = '';
                setTimeout(function() { $('.ui.dropdown').dropdown() }, 50);
            }
        });

        /**自动运行 */
        $scope.auto = function() {
            $scope.getFine();
            $scope.getSector();
            $scope.getSysParam();
            $scope.selectSector(0);
            setTimeout(function() { $('.ui.dropdown').dropdown() }, 50);
        };
        $scope.auto();
    });

});